package com.lalilu.remote

import java.net.DatagramPacket

open class StringUdpService(port: Int, size: Int = 1024) : UdpService(port, size) {

    val serviceId: String by lazy {
        (NetUtils.getMac() ?: System.currentTimeMillis().toString()).md5().take(8)
    }

    fun broadcast(text: String) {
        super.broadcast(packet = "$serviceId: $text".toUdpPacket())
    }

    fun send(text: String, address: String, port: Int, broadcast: Boolean) {
        super.send(packet = "$serviceId: $text".toUdpPacket(address, port), broadcast = broadcast)
    }

    fun startListenStr(callback: (String) -> Unit = {}) {
        super.startListen {
            val msg = transform(it)
            if (!msg.startsWith(serviceId)) {
                callback(msg)
            }
        }
    }

    override suspend fun onReceive(packet: DatagramPacket) {
        packet.runCatching {
            val msg = transform(packet)
            if (!msg.startsWith(serviceId)) {
                onReceive(msg)
            }
        }
    }

    fun transform(packet: DatagramPacket): String {
        return String(packet.data, 0, packet.length).trim()
    }

    open fun onReceive(text: String) {

    }
}